package com.utils;

import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String invokeGet(String uri, int timeout)
            throws ClientProtocolException, IOException {
        return Request.Get(uri).connectTimeout(timeout).useExpectContinue()
                .execute().returnContent().asString();
    }

    public static String invokePost(String uri, Object o, int timeout)
            throws ClientProtocolException, IOException {
        String s_json = JSONObject.valueToString(o);
        return Request.Post(uri).connectTimeout(timeout).useExpectContinue()
                .bodyString(s_json, ContentType.APPLICATION_JSON).execute()
                .returnContent().asString();
    }

    public static String invokePostAddAuth(String uri, Object o, int timeout,
                                           String base64After) throws ClientProtocolException, IOException {
        String s_json = JSONObject.valueToString(o);
        return Request.Post(uri)
                .addHeader("Authorization", "Basic " + base64After)
                .connectTimeout(timeout).useExpectContinue()
                .bodyString(s_json, ContentType.APPLICATION_JSON).execute()
                .returnContent().asString();
    }

    public static Boolean invokePostaddH(String uri, Object o,
                                         int timeout, String base64After)
            throws IOException {

        Boolean t = false;
        String s_json = JSONObject.valueToString(o);
        try {
            Response response = Request.Post(uri)
                    .addHeader("Authorization", "Basic " + base64After)
                    .connectTimeout(timeout).useExpectContinue()
                    .bodyString(s_json, ContentType.APPLICATION_JSON).execute();

            HttpResponse httpResponse = response.returnResponse();
            String xmlContent = EntityUtils.toString(httpResponse.getEntity());// {"is_valid":false,"error":{"code":50011,"message":"expired code"}}

            JSONObject resultObj = new JSONObject(xmlContent);
            logger.info("invokePostaddH response = {}",resultObj.toString());
            if (resultObj.getBoolean("is_valid")) {
                t = true;
            } else {
                JSONObject rete = resultObj.getJSONObject("error");
                logger.error(rete.get("message").toString());
            }

        } catch (Exception e) {

            logger.error("极光验证码发送或验证出现未知错误 :{}", e);

        }
        return t;
    }

    public static String invokePostForm(String uri, Map<String, String> params,
                                        int timeout) throws ClientProtocolException, IOException {
        List<NameValuePair> list = new ArrayList<NameValuePair>();

        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            list.add(new BasicNameValuePair(key, params.get(key)));
        }
        return Request.Post(uri).connectTimeout(timeout).useExpectContinue()
                .bodyForm(list, Consts.UTF_8).execute().returnContent()
                .asString();
    }

}
